package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.apkextract.lib.model.AeCollectManager;
import com.stark.apkextract.lib.model.AeExporter;
import com.stark.apkextract.lib.model.AeUtil;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.ApkBean;
import flc.ast.databinding.ActivityApkDetailsBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.MyUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.GeneralEvtDialog;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class ApkDetailsActivity extends BaseAc<ActivityApkDetailsBinding> {

    public static ApkBean apkBean;
    private boolean isColl = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_apk_details;
    }

    @Override
    protected void initView() {
        mDataBinding.ivApkDetailsBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvApkDetailsPackageName.setOnClickListener(this);
        mDataBinding.ivApkDetailsColl.setOnClickListener(this);
        mDataBinding.llApkDetailsPathCopy.setOnClickListener(this);
        mDataBinding.ivApkDetailsShare.setOnClickListener(this);
        mDataBinding.llApkDetailsExport.setOnClickListener(this);
        mDataBinding.tvApkDetailsLook.setOnClickListener(this);
        mDataBinding.tvApkDetailsUninstall.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvApkDetailsPackageName://复制包名
                ClipboardUtils.copyText(apkBean.pkgName);
                ToastUtils.showShort(R.string.copy_suc);
                break;
            case R.id.ivApkDetailsColl://收藏/取消收藏
                isColl = !isColl;
                mDataBinding.ivApkDetailsColl.setImageResource(isColl ? R.drawable.aysc : R.drawable.ascyy);
                if (isColl) {
                    //添加收藏
                    AeCollectManager.getInstance().addPackageName(apkBean.pkgName);
                } else {
                    //取消收藏
                    AeCollectManager.getInstance().delPackageName(apkBean.pkgName);
                }
                break;
            case R.id.llApkDetailsPathCopy://复制路径
                ClipboardUtils.copyText(AppUtils.getAppPath(apkBean.pkgName));
                ToastUtils.showShort(R.string.copy_suc);
                break;
            case R.id.ivApkDetailsShare://分享
                AeUtil.shareInstalledApk(apkBean.pkgName);
                break;
            case R.id.llApkDetailsExport://导出
                handleExport(apkBean.pkgName);
                break;
            case R.id.tvApkDetailsLook://查看详情
                lookAppDetail(apkBean.pkgName);
                break;
            case R.id.tvApkDetailsUninstall://卸载
                uninstallApp(apkBean.pkgName);
                break;
        }
    }

    @Override
    protected void initData() {
        //图标
        mDataBinding.ivApkDetailsLog.setImageDrawable(AppUtils.getAppIcon(apkBean.pkgName));
        //名称
        mDataBinding.tvApkDetailsName.setText(AppUtils.getAppName(apkBean.pkgName));
        //包名
        mDataBinding.tvApkDetailsPackageName.setText(getString(R.string.packagename_text) + apkBean.pkgName);
        //大小
        long appSize = MyUtils.getAppSize(mContext, apkBean.pkgName);
        mDataBinding.tvApkDetailsSize.setText(getString(R.string.size_text) + ConvertUtils.byte2FitMemorySize(appSize, 0));
        //日期
        long installDate = MyUtils.getInstallDate(mContext, apkBean.pkgName);
        mDataBinding.tvApkDetailsDate.setText(getString(R.string.date_text) + TimeUtils.millis2String(installDate, "yyyy-MM-dd HH:mm"));
        //路径
        mDataBinding.tvApkDetailsPath.setText(AppUtils.getAppPath(apkBean.pkgName));
        //是否收藏
        isColl = AeCollectManager.getInstance().isPackageCollected(apkBean.pkgName);
        mDataBinding.ivApkDetailsColl.setImageResource(isColl ? R.drawable.aysc : R.drawable.ascyy);
    }

    //查看应用详情
    private void lookAppDetail(String packageName) {
        Intent intent = IntentUtils.getLaunchAppDetailsSettingsIntent(packageName);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //卸载应用
    private void uninstallApp(String packageName) {
        new GeneralEvtDialog.Builder(this)
                .title(getString(com.stark.common.res.R.string.prompt))
                .content(getString(R.string.is_uninstall_text) + AppUtils.getAppName(packageName))
                .rightBtnListener(v -> {
                    if (AppUtils.isAppSystem(packageName)) {
                        ToastUtils.showShort(R.string.app_is_system);
                        return;
                    }
                    AppUtils.uninstallApp(packageName);
//                    lookAppDetail(packageName);
                    saveRecord();
                })
                .rightBtnTextColor(Color.parseColor("#0000FF"))
                .build()
                .show();
    }

    //导出安装包
    private void handleExport(String packageName) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //android11及以上版本
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            } else {
                //获得了权限
                exportAfterGetPermission(packageName);
            }
        } else {
            //android11及以下版本（android 10及android 11需在AndroidManifest中设置requestLegacyExternalStorage为true）
            StkPermissionHelper.reqManageExternalStoragePermission()
                    .reqPermissionDesc(getString(R.string.get_import_permission))
                    .callback(new StkPermissionHelper.ACallback() {
                        @Override
                        public void onGranted() {
                            exportAfterGetPermission(packageName);
                        }
                    }).request();
        }
    }

    //导出连招1
    private void exportAfterGetPermission(String packageName) {
        boolean isExist = AeExporter.getInstance().isExportExist(packageName);
        if (isExist) {
            //已存在
            String apkFileName = AeExporter.getExportFileName(packageName);
            String exportRootDir = AeExporter.getExportRootDir();
            String content = getString(R.string.ae_apk_exist_tip_fmt, apkFileName, exportRootDir);
            new GeneralEvtDialog.Builder(this)
                    .title(getString(com.stark.common.res.R.string.prompt))
                    .content(content)
                    .leftBtnText(getString(com.stark.common.res.R.string.cover))
                    .leftBtnListener(v -> {
                        startExport(packageName);
                    })
                    .rightBtnText(getString(com.stark.common.res.R.string.no_cover))
                    .rightBtnTextColor(Color.parseColor("#0000FF"))
                    .build()
                    .show();
            return;
        }

        //不存在
        String appName = AppUtils.getAppName(packageName);
        String exportRootDir = AeExporter.getExportRootDir();
        String content = getString(R.string.ae_apk_not_exist_tip_fmt, appName, exportRootDir);
        new GeneralEvtDialog.Builder(this)
                .title(getString(com.stark.common.res.R.string.prompt))
                .content(content)
                .rightBtnListener(v -> {
                    startExport(packageName);
                })
                .rightBtnTextColor(Color.parseColor("#0000FF"))
                .build()
                .show();
    }

    //导出连招2
    private void startExport(String packageName) {
        showDialog(getString(com.stark.common.res.R.string.exporting));
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                emitter.onNext(AeExporter.getInstance().export(packageName));
            }

            @Override
            public void accept(Boolean success) {
                if (success != null && success) {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.export_success));
                } else {
                    ToastUtils.showShort(getString(com.stark.common.res.R.string.export_failure));
                }
                dismissDialog();
            }
        });
    }

    private void saveRecord() {
        List<ApkBean> listSp = AppSpUtils.getUninstallRecordList();
        if (listSp == null) listSp = new ArrayList<>();
        listSp.add(0, apkBean);
        AppSpUtils.saveUninstallRecordList(listSp);
    }

}